'use strict';

angular.module('App').controller('AppListController', ['$scope', '$state', 'ParameterService', 'BaseSocket', 'BaseFunction', 'BaseClass', 'BaseModule', 'BaseEnum', 'BaseService', 'EntityService', '$location', 'Authentication',
    function($scope, $state, ParameterService, BaseSocket, BaseFunction, BaseClass, BaseModule, BaseEnum, BaseService, EntityService, $location, Authentication) {
        $scope.DeviceTypeEnum = BaseFunction.getEnum('AppEnum.DeviceType');

        var serverUrl = "";
        var publicSocket;
        BaseSocket.connect(function(skt){
            publicSocket = skt;
        });
        var round = new BaseClass.Round();

        BaseModule.initModule($scope, '_App');
        $scope.Module._App.PageSize = 15;

        BaseModule.initModule($scope, 'App');
        $scope.Module.App.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;

        $scope.DownloadStatus = {
            No: 0,              //最新版本
            Downloadable: 1,    //可下载
            Updatable: 2,       //可更新
            Downloading: 3      //下载中
        };

        ParameterService.getParameterValue('DownloadServer', function(dataUrl){
            serverUrl = dataUrl;

            //请求下载服务器传入数据，目前还没用到
            var reqData = {
                EnterpriseID: ''    //企业ID
            };

            BaseFunction.httpRequest(serverUrl + "/api/App/getApps", reqData, function(data){
                $scope.Module.App.load(null, null, function(){
                    var records = data;
                    for(var i=0; i<records.length; i++){
                        if(records[i].FileSize){
                            records[i]._FileSize = records[i].FileSize / 1024 / 1024;   //显示字段
                        }
                        else{
                            records[i]._FileSize = 0;
                        }

                        var isFind = false;
                        for(var j=0; j<$scope.Module.App.Records.length; j++){
                            if(records[i].AppID == $scope.Module.App.Records[j].AppID){
                                isFind = true;
                                records[i]["CurrentRecordId"] = $scope.Module.App.Records[j]._id;
                                records[i]["CurrentVersion"] = $scope.Module.App.Records[j].Version;
                                records[i]["IsSync"] = $scope.Module.App.Records[j].IsSync;
                                if(records[i].Version != $scope.Module.App.Records[j].Version){
                                    records[i]["DownloadStatus"] = $scope.DownloadStatus.Updatable;    //可更新
                                }
                                else{
                                    records[i]["DownloadStatus"] = $scope.DownloadStatus.No;    //最新版本，无需下载
                                }
                                break;
                            }
                        }
                        if(!isFind){
                            records[i]["CurrentRecordId"] = null;
                            records[i]["IsSync"] = true;
                            records[i]["DownloadStatus"] = $scope.DownloadStatus.Downloadable;     //可下载
                        }
                    }
                    $scope.Module._App.Records = records;
                    $scope.Module._App.emitOnLoadEvent();
                });
            }); 
        });

        $scope.btnSyncAll = function(){
            //获取内网地址
            BaseService.getSysConstValue('Intranet', function(dataUrl){
                var serverUrl = dataUrl.HostName + ':' + dataUrl.Port;
                $scope.Module.App.find({IsEffective: true, IsSync: {$ne: true}}, null, null, function(records){
                    if(records.length > 0){
                        for(var i=0; i<records.length; i++){
                            delete records[i]["_id"];
                            delete records[i]["RowStatus"];
                            delete records[i]["IsHide"];
                            delete records[i]["IsSelected"];
                            delete records[i]["IsSync"];
                        }
                        BaseFunction.httpRequest(serverUrl + "/api/App/updateApps", {Apps: records}, function(data){
                            EntityService.updateByValue('App', {IsEffective: true}, {$set: {IsSync: true}}, function(data){
                                $state.reload();
                                BaseFunction.tip("同步完成", "操作提示");
                            });
                        });
                    }
                });
            });
        };

        //下载全部，只下载当前页数据，跨页会有进度条div没有被创建的问题
        $scope.btnDownloadAll = function(){
            var tables = document.getElementsByTagName('table');
            for(var i=0; i<tables.length; i++){
                if(tables[i].getAttribute('class') == 'TableBody'){
                    if(tables[i].rows.length > 0) {
                        BaseFunction.loading(true);
                        var downCount = 0;
                        var downComplete = function () {
                            downCount++;
                            if (downCount == tables[i].rows.length) {
                                BaseFunction.loading(false);
                            }
                        }
                        for (var j = 0; j < tables[i].rows.length; j++) {
                            $scope.download(
                                $scope.Module._App.findRecordById(tables[i].rows[j].getAttribute('key')),
                                tables[i].rows[j].cells[tables[i].rows[0].cells.length - 1].children[0].children[3],
                                downComplete
                            );
                        }
                    }
                    break;
                }
            }
        }
        $scope.download = function(record, scheduleDiv, completeFun){
            //全部下载时，用来判断不用下载的记录
            if(record.DownloadStatus == $scope.DownloadStatus.No){
                if(completeFun){
                    completeFun();
                }
                return;
            }

            var serverPath = serverUrl + "/api/App/getFileStream";

            var focusedRecord= null;    //当前数据库记录
            if(record.CurrentRecordId != null){
                focusedRecord = $scope.Module.App.findRecordById(record.CurrentRecordId);
                $scope.Module.App.FocusedRecord = focusedRecord;
            }

            var isErrDisplayImg = false,
                isUploadDisplayImg = false; //上传动作是否完成
            if(record.DisplayImage != null && record.DisplayImage != undefined && record.DisplayImage.trim() != ""
                && (focusedRecord == null || record.DisplayImage != focusedRecord.DisplayImage)){
                var deleteDownDisplayImg = null;    //删除显示图片文件名
                if(focusedRecord != null){
                    deleteDownDisplayImg = focusedRecord.MouseDownImage;
                }

                BaseService.downloadFile(serverPath, record.DisplayImage,
                 null, deleteDownDisplayImg, null, function(data){
                    if(data.Error){
                        isErrDisplayImg = true;
                        console.log("下载显示图标" + record.DisplayImage + "出错，可尝试重现下载\n\r出错信息：" + data.Error.message);
                    }
                    isUploadDisplayImg = true;
                    updateReord();
                });
            }
            else{
                isUploadDisplayImg = true;
            }

            var isErrMouseImg = false,
                isUploadDownMouseImg = false;   //上传动作是否完成         
            if(record.MouseDownImage != null && record.MouseDownImage != undefined && record.MouseDownImage.trim() != ""
                && (focusedRecord == null || record.MouseDownImage != focusedRecord.MouseDownImage)){
                var deleteDownMouseImg = null;      //删除鼠标按下图片文件名
                if(focusedRecord != null){
                    deleteDownMouseImg = focusedRecord.MouseDownImage;
                }

                BaseService.downloadFile(serverPath, record.MouseDownImage,
                 null, deleteDownMouseImg, null, function(data){
                    if(data.Error){
                        isErrMouseImg = true;
                        console.log("下载按下图标" + record.MouseDownImage + "出错，可尝试重现下载\n\r出错信息：" + data.Error.message);
                    }
                    isUploadDownMouseImg = true; 
                    updateReord();
                });
            }
            else{
                isUploadDownMouseImg = true; 
            }
            // var CircleElement = event.srcElement.parentElement.children[2].children[0];
            // var Circle = function(progress){
            //     var ctx = CircleElement.getContext("2d");
            //     ctx.lineWidth = 2;
            //     ctx.strokeStyle = "#0000ff";
            //     // ctx.font = '10pt';
            //     // ctx.fillText("5%", 7, 17);
            //     ctx.beginPath();
            //     ctx.arc(13, 13, 11, Math.PI * 1.5, (-0.5 + 2 * progress + 2) * Math.PI, false);
            //     ctx.stroke();
            // };

            var isErrDownFile = false,
                isUploadFile = false;   //上传动作是否完成
            if(record.FileName != null && record.FileName != undefined && record.FileName.trim() != ""
                && (focusedRecord == null || record.FileName != focusedRecord.FileName)){
                record.DownloadStatus = $scope.DownloadStatus.Downloading;  //下载中
                //获取上传进度条Element
                var divElement = null;
                if(event.srcElement.innerText == "全部下载"){
                    divElement = scheduleDiv;
                } 
                else{
                    divElement = event.srcElement.parentElement;
                    while(divElement.tagName.toLowerCase() != "div"){
                        divElement = divElement.parentElement;
                    }
                    divElement =  divElement.children[3];
                }

                if(divElement != null){
                    divElement.innerText = "0%";
                    divElement.style.width = "0%";
                    divElement.style.display = '';
                }

                var deleteFileName = null;      //删除文件名
                if(focusedRecord != null){
                    deleteDownMouseImg = focusedRecord.FileName;
                }

                var downloadSize = 0;                
                publicSocket.on(record.FileName + "_DownloadSize", function(size) {
                    downloadSize += size;
                    // Circle(downloadSize / record.FileSize);
                    if(divElement != null){
                        divElement.innerText = round.formatPercent(downloadSize / record.FileSize);
                        divElement.style.width = (downloadSize / record.FileSize * 100).toString() + "%";
                    }
                });
                publicSocket.on(record.FileName + "_DownloadComplete", function(IsDownload) {
                    if(IsDownload){
                        //Circle(1);
                        if(divElement != null){
                            divElement.style.width = "100%";
                            divElement.innerText = "100%";
                        }
                    }
                    else{
                        if(divElement != null){
                            divElement.style.width = "0%";
                            divElement.innerText = "";
                        }
                        console.log("下载App包" + record.FileName + "出错，可尝试重现下载");
                    }
                    
                    // divElement.style.display = 'none';
                });

                BaseService.downloadFile(serverPath, record.FileName, null, deleteFileName, publicSocket.Socket.id, function(data){
                    if(data.Error){
                        isErrDownFile = true;
                        console.log("下载App包" + record.FileName + "出错，可尝试重现下载\n\r出错信息：" + data.Error.message);
                    }
                    isUploadFile = true;
                    updateReord();
                });
            }
            else{
                isUploadFile = true;
                if(completeFun){
                    completeFun();
                }
            }

            var updateReord = function(){
                if(isUploadFile && isUploadDownMouseImg && isUploadDisplayImg){
                    if(!isErrDownFile || !isErrMouseImg || !isErrDisplayImg){
                        if(focusedRecord == null){
                            //新增Record
                            focusedRecord = $scope.Module.App.add();
                        }
                        else{
                            focusedRecord.RowStatus = BaseEnum.RowStatus.Modify.Value;
                        }
                        focusedRecord["AppID"] = record.AppID;
                        focusedRecord["Name"] = record.Name;
                        if(!isErrDownFile && !isErrMouseImg && !isErrDisplayImg){
                            focusedRecord["Version"] = record.Version;
                        }                        
                        if(!isErrDownFile){
                            focusedRecord["FileName"] = record.FileName;
                            focusedRecord["FileSize"] = record.FileSize;
                        }
                        if(!isErrDisplayImg){
                            focusedRecord["DisplayImage"] = record.DisplayImage;
                            focusedRecord["DisplayImageSize"] = record.DisplayImageSize;
                        }
                        if(!isErrMouseImg){
                            focusedRecord["MouseDownImage"] = record.MouseDownImage;
                            focusedRecord["MouseDownImageSize"] = record.MouseDownImageSize;
                        }                        
                        focusedRecord["Describe"] = record.Describe;
                        focusedRecord["Remark"] = record.Remark;
                        focusedRecord["IsEffective"] = record.IsEffective;
                        focusedRecord["IsShared"] = record.IsShared;
                        focusedRecord["IsSync"] = false;
                        focusedRecord["Type"] = record.Type;

                        $scope.Module.App.save(function(){
                            if(!isErrDownFile && !isErrMouseImg && !isErrDisplayImg){
                                record["CurrentVersion"] = focusedRecord.Version;
                                record.DownloadStatus = $scope.DownloadStatus.No;
                                record.IsSync = false;
                                $scope.Module._App.emitRowsDataChangeEvent([record]);
                            }
                            else{
                                record.DownloadStatus = $scope.DownloadStatus.Updatable;
                            }
                        });
                    }
                }

                if(completeFun){
                    completeFun();
                }
            };
        };

        $scope.delete = function(record){
            if($scope.Module._App.FocusedRecord.CurrentRecordId != null){
                $scope.Module.App.FocusedRecord = $scope.Module.App.findRecordById($scope.Module._App.FocusedRecord.CurrentRecordId);
                $scope.Module.App.delete(function(){
                    $scope.Module._App.FocusedRecord.CurrentRecordId = null;
                    $scope.Module._App.FocusedRecord.CurrentVersion = "";
                    $scope.Module._App.FocusedRecord.DownloadStatus = $scope.DownloadStatus.Downloadable;
                });
            }
        };

        var DownloadFile = function(serverPath, downloadPath, downloadFileName, uploadPath, fileName, fileSize, deleteFileName, isDownloadable, isUpdatable){
            this.ServerPath = serverPath;
            this.DownloadPath = null;
            this.DownloadFileName = downloadFileName;
            this.UploadPath = null;
            this.FileName = null;
            this.FileSize = fileSize;
            this.DeleteFileName = deleteFileName;
            this.IsDownloadable = isDownloadable;
            this.IsUpdatable = isUpdatable;

            this.CircleElement = null;
            this.IsDownloading = false;

            if(this.ServerPath == null || this.ServerPath == undefined){
                // var serverUrl = "http://10.1.217.3:3000";
                // this.ServerPath = serverUrl + "/api/base/getFileStream";
            }
            if(downloadPath != null && downloadPath != undefined){
                this.DownloadPath = downloadPath;
            }
            if(uploadPath != null && uploadPath != undefined){
                this.UploadPath = uploadPath;
            }
            if(fileName != null && fileName != undefined){
                this.FileName = fileName;
            }

            this.download = function(downloadHandle){
                this.IsDownloading = true;

                var publicSocket = null;
                if(this.FileSize != null && this.FileSize != undefined && this.FileSize > 0){
                    this.Circle(0);
                    this.CircleElement = event.srcElement.parentElement.children[2].children[0];
                    var downloadSize = 0;
                    var self = this;
                    BaseSocket.connect(function(skt){
                        publicSocket = skt;
                        publicSocket.on(self.FileName + "_DownloadSize", function(size) {
                            downloadSize += size;
                            self.Circle(downloadSize / $scope.filesize);
                        });
                        publicSocket.on(self.FileName + "_DownloadComplete", function(IsDownload) {
                            if(IsDownload){
                                self.Circle(1);
                                self.IsDownloadable = false;
                                self.IsUpdatable = false;
                            }
                            else{
                                BaseFunction.alert("下载出错，文件没有下载完，请重新下载", "下载失败");
                            }
                            self.IsDownloading = false;
                        });

                        
                        BaseService.downloadFile(self.ServerPath, self.DownloadPath, self.DownloadFileName, self.UploadPath,
                         self.FileName, self.DeleteFileName, publicSocket.Socket.id, function(data){
                            if(data.Error){
                                BaseFunction.alert(data.Error.message, data.Error.title);
                            }
                            else{
                                if(downloadHandle){
                                    downloadHandle(data);
                                }
                            }
                        });
                    });
                }
            };

            this.Circle = function(progress){
                var ctx = this.CircleElement.getContext("2d");
                ctx.lineWidth = 2;
                ctx.strokeStyle = "#0000ff";
                // ctx.font = '10pt';
                // ctx.fillText("5%", 7, 17);
                ctx.beginPath();
                ctx.arc(13, 13,  11, Math.PI * 1.5, (-0.5 + 2 * progress + 2) * Math.PI, false);
                ctx.stroke();
            };
        }
    }
]);
